<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input placeholder="请您输入SPU的名称" v-model="spuParams.spuName"></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌" style="width: 50%">
      <el-select v-model="spuParams.tmId">
        <el-option v-for="(item) in AllTradeMark"
                   :key="item.id" :label="item.tmName" :value="item.id"></el-option>
        <!--        <el-option label="华为"></el-option>-->
        <!--        <el-option label="OPPO"></el-option>-->
        <!--        <el-option label="Vivo"></el-option>-->
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input type="textarea" v-model="spuParams.description"></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <!--v-model:fileList:展示默认图片-->
      <!--action:上传的服务器-->
      <!--on-preview:点击预览时，执行的方法-->
      <el-upload v-model:file-list="imgList"
                 list-type="picture-card" action="/api/admin/product/fileUpload"
                 :on-preview="handlerPictureCardPreview">
        <el-icon>
          <Plus/>
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img :src="previewPictureUrl" alt="Preview Img" width="100%" height="100%">
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <!--展示销售属性的下拉菜单-->
      <el-select v-model="saleAttrIdAndValueName" style="width: 50%"
                 :placeholder="`还有${unSelectSaleAttr.length}个属性可以选择`">
        <el-option :value="`${item.id}:${item.name}`" v-for="(item) in unSelectSaleAttr"
                   :key="item.id" :label="item.name"></el-option>
      </el-select>
      <el-button :disabled="!saleAttrIdAndValueName" type="primary" icon="Plus" style="margin:0 10px"
                 @click="addSaleAttr(saleAttrIdAndValueName)">添加属性
      </el-button>
      <!--table展示销售属性与属性值-->
      <el-table stripe border style="margin: 10px 0" :data="saleAttrs">
        <el-table-column align="center" type="index" label="序号" width="80px"></el-table-column>
        <el-table-column label="属性名" width="120px" prop="saleAttrName"></el-table-column>
        <el-table-column label="属性值">
          <template #="{row}">
            <el-tag v-for="(item,$index) in row.spuSaleAttrValueList" @close="row.spuSaleAttrValueList.splice($index,1)"
                    :key="item.id" style="margin: 0 5px" closable>
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input v-model="row.saleAttrValue" @blur="toLook(row)" v-if="row.flag==true" placeholder="请输入属性值"
                      size="small" style="width: 100px;"></el-input>
            <el-button @click="toEdit(row)" v-else size="small" icon="Plus" type="success"
                       style="margin: 0 5px"></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100px">
          <template #="{$index}">
            <el-button type="danger" size="small" icon="Delete" @click="saleAttrs.splice($index,1)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="save" :disabled="!saleAttrs.length">保存</el-button>
      <el-button type="danger" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import {ref, computed} from "vue";
//触发自定义事件
//@ts-ignore
import {
  T_HasSaleAttr,
  T_SaleAttr,
  T_SaleAttrValue,
  T_SpuData,
  T_SpuImage,
  T_Trademark
  //@ts-ignore
} from "@/api/product/spu/type.ts";

import {
  reqAllTradeMark,
  reqSpuImageList,
  reqSpuHasSaleAttr,
  reqGetAllSaleAttr,
  reqAddOrUpdateSpu,
  //@ts-ignore
} from "@/api/product/spu/spuApi.ts";
//@ts-ignore
import type {
  T_AllTradeMarkResponse,
  T_SpuImageResponse,
  T_SaleAttrResponseData,
  T_SaleAllAttrResponse
  //@ts-ignore
} from "@/api/product/spu/type.ts";
import {ElMessage} from "element-plus";

let $emit = defineEmits(['changeScene']);
//存储已有的SPU数据
let AllTradeMark = ref<T_Trademark[]>([]);
//商品的图片
let imgList = ref<T_SpuImage[]>([]);
//已有的SPU销售属性
let saleAttrs = ref<T_SaleAttr[]>([]);
//全部的销售属性
let allSaleAttr = ref<T_HasSaleAttr[]>([]);
//存储已有的SPU对象
let spuParams = ref<T_SpuData>({
  category3Id: "",//三级分类ID
  spuName: "",//spu名字
  description: "",//spu描述
  tmId: '',//品牌id
  spuImageList: [],//照片墙
  spuSaleAttrList: [],//spu属性值
});
//控制对话框的显示与隐藏
let dialogVisible = ref<boolean>(false);
//存储预览图片的地址
let previewPictureUrl = ref<string>("");
//收集未选择的还未选择的销售属性的ID与属性值的名字
let saleAttrIdAndValueName = ref<string>("");


//取消按扭的回调
const cancel = () => {
  //点击取消按扭，通知父组件切换场景为1,展示已有的SPU数据
  $emit('changeScene', {scene: 0, params: "update"});
}

//发送请求获取完整的spu数据
const initSpuData = async (spu: T_SpuData) => {
  //存取父组件传递过来的spu数据
  spuParams.value = spu;
  //spu:父组件传过来的SPU对象【不完整】
  //发送请求收集完整的数据
  let resultAllTradeMark: T_AllTradeMarkResponse = await reqAllTradeMark();
  //获取某个品牌下的全部售卖的图片
  let resultTradeMarkImgs: T_SpuImageResponse = await reqSpuImageList(spu.id as number)
  //获取已有的SPU销售属性的数据
  let resultHasAttrs: T_SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number)
  //获取整个项目全部SPU的销售属性
  let resultAllAttrs: T_SaleAllAttrResponse = await reqGetAllSaleAttr()

  //存储对应的属性
  AllTradeMark.value = resultAllTradeMark.data;
  imgList.value = resultTradeMarkImgs.data.map((item: any) => {
    return {//将imgName变成name，将imgUrl变成url
      name: item.imgName,
      url: item.imgUrl
    }
  });
  saleAttrs.value = resultHasAttrs.data;
  allSaleAttr.value = resultAllAttrs.data;

}


//点击预览执行的回调
const handlerPictureCardPreview = (file: any) => {
  //给预览图片的地址传入参数
  previewPictureUrl.value = file.url;
  //对话框弹出
  dialogVisible.value = true;
}

//计算出还没有选择的销售属性
//根据allSaleAttr - saleAttrs
let unSelectSaleAttr = computed(() => {
  //全部的销售属性：根据allSaleAttr
  //已有的销售属性：saleAttrs
  //全部属性：颜色、版本、尺码
  // 已有的属性：颜色、版本
  /**
   * 全为true才会过滤出来
   * 第一次循环：颜色：
   * 内层循环：颜色!=颜色  false
   *         颜色!=版本  true
   * 第二次循环：版本：
   * 内层循环：版本!=颜色 true
   *         版本!=版本 false
   * 第三次循环：尺码：
   * 内层循环：尺码 !=颜色 true
   *         尺码!=版本 true
   *         过滤出来
   */
  let unSelectArr = allSaleAttr.value.filter(item => {
    return saleAttrs.value.every(item1 => {
      //先遍历外面所有的属性，对每个属性判断： 再遍历已有的属性， 返回true时， 就会未选择的属性赋值给：unSelectArr
      return item.name != item1.saleAttrName;
    })
  })
  return unSelectArr;
})

//添加属性的方法回调
const addSaleAttr = (newAttrValue: any) => {
  /**
   * baseSaleAttrId:num
   * saleAttrName:string
   * spuSaleAttrValueList:T_SaleAttrValue[]
   */
      //整理格式
  const [baseSaleAttrId, saleAttrName] = newAttrValue.split(':')
  //封装成一个新的销售属性对象
  let newSaleAttr: T_SaleAttr = {
    //KV一致省略V
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: []
  }
  //追加到数组当中
  saleAttrs.value.push(newSaleAttr)
  //清空选择框中收集的数据
  saleAttrIdAndValueName.value = "";
}

//添加属性转成编辑模式的回调
const toEdit = (row: T_SaleAttr) => {
  row.flag = true;//flag为true input框出来
  row.saleAttrValue = ""
  console.log(row)
}

//从编辑模式转成查看模式
const toLook = (row: T_SaleAttr) => {

  //整理收集的属性的ID与属性值的名字
  const {baseSaleAttrId, saleAttrValue} = row;
  //整理数据结构
  let newSaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue,
  }
  //非法清空判断
  if (saleAttrValue.trim() == '') {
    //错误提示
    ElMessage({
      type: 'error',
      message: "属性值不能为空!"
    })
    return;
  }
  //判断属性值是否重复
  let repeat = row.spuSaleAttrValueList.find(((item: T_SaleAttrValue) => {
        return item.saleAttrValueName == saleAttrValue
      })
  )
  if (repeat) {
    ElMessage({
      type: 'error',
      message: '属性值重复'
    })
    return;
  }

  //将收集到的数据push到属性数组
  row.spuSaleAttrValueList.push(newSaleAttrValue);
  //切换回查看模式
  row.flag = false;
}


//保存按扭的回调
const save = async () => {
  //整理参数
  //1.照片墙的数据
  //spuParams.value.spuImageList = imgList.value; //记得换字段名和url：服务器的地址
  spuParams.value.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    }
  });
  //2.销售属性的数据
  spuParams.value.spuSaleAttrList = saleAttrs.value;
  //发送请求
  let result = await reqAddOrUpdateSpu(spuParams.value);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: spuParams.value.id ? "更新数据成功" : "添加数据成功"
    });
    //切换场景
    $emit('changeScene', {scene: 0, paramas: spuParams.value.id ? "update" : "add"});
  } else {
    ElMessage({
      type: "error",
      message: spuParams.value.id ? "更新数据失败" : "添加数据失败"
    });
  }

}

//添加一个新的spu初始化请求方法
const initAddSpu = async (c3Id: number | string) => {
  //清空数据
  Object.assign(spuParams.value, {
    category3Id: "",//三级分类ID
    spuName: "",//spu名字
    description: "",//spu描述
    tmId: '',//品牌id
    spuImageList: [],//照片墙
    spuSaleAttrList: [],//spu属性值
  })
  imgList.value = [];
  saleAttrs.value = [];
  saleAttrIdAndValueName.value = "";

  //存储三级分类id
  spuParams.value.category3Id = c3Id;
  //获取所有品牌的数据
  let resultAllTradeMark: T_AllTradeMarkResponse = await reqAllTradeMark();
  //获取整个项目全部SPU的销售属性
  let resultAllAttrs: T_SaleAllAttrResponse = await reqGetAllSaleAttr();
  //存储数据
  AllTradeMark.value = resultAllTradeMark.data;
  allSaleAttr.value = resultAllAttrs.data;
}

//对外暴露
defineExpose({initSpuData, initAddSpu})
</script>

<style scoped>

</style>